import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mall/constant/app_colors.dart';
import 'package:mall/constant/app_strings.dart';
import 'package:mall/constant/text_style.dart';
import 'package:mall/gen/r.dart';
import 'package:mall/modules/model/cart_entity.dart';
import 'package:mall/modules/sc/cart_sc.dart';
import 'package:mall/modules/service/cart_service.dart';
import 'package:mall/ui/page/goods/widgets/goods_price_widget.dart';
import 'package:mall/ui/widgets/cached_image.dart';
import 'package:mall/ui/widgets/cart_number.dart';
import 'package:mall/ui/widgets/default_bg.dart';
import 'package:mall/utils/alert/alert_util.dart';
import 'package:mall/utils/image_component/image_component.dart';
import 'package:mall/utils/list_placeholder_component/list_placeholder_component.dart';
import 'package:mall/router/navigator_util.dart';
import 'package:mall/utils/refresh/refresh_widget.dart';
import 'package:mall/utils/refresh/warp_refresh_controller.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

class TabCartPage extends StatefulWidget {
  @override
  _TabCartPageState createState() => _TabCartPageState();
}

class _TabCartPageState extends State<TabCartPage> {
  // CartViewModel _cartViewModel;
  final sc_cart = Get.put(CartSc());
  late final _refreshController = WarpRefreshController(loadState: sc_cart.loadState, initialRefresh: false);

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return APPScaffold(
      title: '购物车',
      body: _contentView(),
      bottomNavigationBar: _bottomWidget(),
    );
  }

  Widget _contentView() {
    return Obx(
      () {
        final cartList = sc_cart.data.value?.cartList ?? [];
        return RefreshComponent(
          controller: _refreshController,
          onRefresh: () => sc_cart.refreshData(),
          child: WrappedListPlaceholderComponent.widget1(
            data: cartList,
            state: sc_cart.loadState.value,
            builder: (p0) => ListView.builder(
              itemCount: p0.length,
              itemBuilder: (BuildContext context, int index) {
                return _cartItemView(p0[index], index);
              },
            ),
          ),
        );
      },
    );
  }

  Widget _cartItemView(CartBean cartBean, int index) {
    return Container(
        margin: EdgeInsets.only(left: 15, right: 15, top: 5),
        width: double.infinity,
        child: Slidable(
          child: Card(
            color: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              padding: EdgeInsets.only(right: 5, top: 10, bottom: 10),
              child: Row(
                children: <Widget>[
                  //选中
                  InkWell(
                    onTap: () {
                      if (cartBean.productId == null) {
                        return;
                      }
                      CartService.cartCheck([cartBean.productId!], !(cartBean.checked ?? true));
                    },
                    child: Container(
                      padding: EdgeInsets.all(10),
                      child: ImageComponent(
                        cartBean.checked ?? true ? R.image.selectCircleTrue.path : R.image.selectCircleFalse.path,
                        size: 20,
                      ),
                    ),
                  ),
                  //图片
                  CachedImageView(75, 75, cartBean.picUrl),
                  SizedBox(width: 10),
                  //内容
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        //标题
                        Text(
                          cartBean.goodsName ?? "",
                          style: FMTextStyle.color_222222_size_13,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),

                        //选择的规格
                        SizedBox(height: 5),
                        Text(
                          "${AppStrings.SPECIFICATIONS}:${cartBean.specifications?.join(',') ?? ''}",
                          style: FMTextStyle.color_999999_size_12,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        //价格和数量
                        SizedBox(height: 5),
                        Row(
                          children: [
                            //价格
                            // Text("${AppStrings.DOLLAR}${cartBean.price}", style: FMTextStyle.color_ff5722_size_13),
                            GoodsPriceWidget(price: cartBean.price, priceFontSize: 15),
                            Spacer(),
                            CartNumberView(
                              cartBean.number,
                              (value) {
                                print(value);
                                CartService.updateCart(
                                  cartId: cartBean.id!,
                                  number: value,
                                  productId: cartBean.productId!,
                                  goodsId: cartBean.goodsId!,
                                );
                              },
                            )
                          ],
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
          startActionPane: ActionPane(
            extentRatio: 0.2,
            motion: const ScrollMotion(), // 滑动动画
            children: [
              SlidableAction(
                onPressed: (context) {
                  // 删除操作逻辑
                  _deleteDialog(cartBean.productId, index);
                },
                backgroundColor: AppColors.C_FF5722,
                foregroundColor: Colors.white,
                icon: Icons.delete,
                label: AppStrings.DELETE,
                padding: EdgeInsets.zero,
                borderRadius: BorderRadius.all(
                  Radius.circular(10),
                ),
              ),
            ],
          ),
        ));
  }

  _deleteDialog(int? productId, int index) {
    if (productId == null) {
      return;
    }

    AlertUtil.showAlert(
      context,
      content: '是否确认删除该商品',
      onConfirm: () {
        _deleteCartItem(productId, index);
      },
    );
  }

//底部
  Widget _bottomWidget() {
    return Obx(() {
      if (sc_cart.data.value?.cartList == null || sc_cart.data.value?.cartList!.length == 0) {
        return Container();
      }
      return Container(
        height: 55,
        decoration: ShapeDecoration(
          shape: Border(top: BorderSide(color: AppColors.C_F0F0F0, width: 1.0)),
          color: AppColors.C_FFFFFF,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            //选中
            Obx(
              () => InkWell(
                onTap: () {
                  _setCheckAll(!sc_cart.isAllCheck.value);
                },
                child: Container(
                  padding: EdgeInsets.all(10),
                  child: ImageComponent(
                    sc_cart.isAllCheck.value ? R.image.selectCircleTrue.path : R.image.selectCircleFalse.path,
                    size: 20,
                  ),
                ),
              ),
            ),
            Text('全选', style: APPTextStyle.color_222222_size_13),
            Spacer(),
            Row(
              children: [
                //合计
                Text('合计:', style: APPTextStyle.color_222222_size_13),
                SizedBox(width: 5),
                //价格
                GoodsPriceWidget(price: sc_cart.data.value?.cartTotal?.checkedGoodsAmount, priceFontSize: 20),
                SizedBox(width: 15),
                ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor: WidgetStateProperty.all(AppColors.C_FF5722),
                    elevation: WidgetStateProperty.all(0),
                    textStyle: WidgetStateProperty.all(
                      TextStyle(color: AppColors.C_FFFFFF, fontSize: 13),
                    ),
                  ),
                  onPressed: () {
                    NavigatorUtil.goFillInOrder(0);
                  },
                  child: Text(AppStrings.GO_PAY, style: FMTextStyle.color_ffffff_size_13),
                ),
                SizedBox(width: 15),
              ],
            ),
          ],
        ),
      );
    });
  }

  _deleteCartItem(int productId, int index) {
    CartService.deleteCart([productId]);
  }

  _setCheckAll(bool check) {
    //获取到所有选中的 id
    final ids = sc_cart.getCheckedIds(check);
    if (ids.isNotEmpty) {
      CartService.cartCheck(ids, check);
    }
  }
}
